import {
  request
} from '../../request/index.js'

// pages/active/active.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    http: '',
    user: {},
    orderList: [],
    remark:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    //通过缓存处理来减少请求次数
    const orderList = wx.getStorageSync('orderList');
    if (!orderList) {
      console.log(1111);
      this.getData();
    } else {
      if (Date.now() - orderList.time > 1000 * 600) {
        console.log(2222);
        //如果超过自己定义的时间则重新发送请求
        this.getData();
      } else {
        console.log(3333);
        //如果没有超过时间则可用缓存中的数据
        this.setData({
          orderList: orderList.data.reverse()
        })
      }
    }
  },
  //点击进入订单详情页面
  detailClick(e) {
    request({
      url: 'Order/getOrderById',
      data: {
        order_code: e.currentTarget.dataset.id
      },
    }).then((result) => {
      console.log(result);
      wx.setStorageSync('orderDetail', result.data.data);

      // this.setData({
      //   text:result.data.data.order_remark
      // })
      wx.navigateTo({
        url: '../../pages/orderDetail/orderDetail'
      })
    });
  },

  //刷新
  onRefresh() {
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading();
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    wx.showLoading({
      title: '刷新中...',
    })
    this.getData();
  },
  //获取数据
  getData() {
    let user = wx.getStorageSync('user');
    // let user = typeof wx.getStorageSync('user') === 'string' ? JSON.parse(wx.getStorageSync('user')) : wx.getStorageSync('user');
    this.setData({
      http: app.globalData.http,
      user
    });
    if (Object.keys(this.data.user).length != 0 && this.data.user != '') {
      request({
        url: 'Order/getOrderListByUserId',
        data: {
          user_id: this.data.user.user_id
        }
      }).then((result) => {
        console.log(result);
        wx.setStorageSync('orderList', {
          time: Date.now(),
          data: result.data.data
        })
        let orderList = result.data.data.reverse();
        this.setData({
          orderList
        })
      }).then((res) => {
        setTimeout(() => {
          //隐藏loading 提示框
          wx.hideLoading();
          //隐藏导航条加载动画
          wx.hideNavigationBarLoading();
          //停止下拉刷新
          wx.stopPullDownRefresh();
        }, 1000)
      })
    }


  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    //调用刷新时将执行的方法
    this.onRefresh();
  }
})